<?php
include_once('../../php/postgre.php');

$act = '';
if(isset($_POST['act'])) $act = $_POST['act'];
if($act=='save_desa'){
	$id_desa = $_POST['id_desa'];
	$id_kecamatan = $_POST['id_kecamatan'];
	$nama_desa = $_POST['nama_desa'];
	
	if(!is_numeric($id_desa) || !is_numeric($id_kecamatan) ){
		echo "Err: invalid id.";
		exit;
	}
	
	if($id_desa>0){
		exec_query("update mus_desa set id_kecamatan=".$id_kecamatan.", nama_desa='".$nama_desa."' where iddesa=".$id_desa);
		echo 'success__';
		logs('Mengubah keterangan Desa','Nama Desa '.$nama_desa);
	}else{
		$maxid = get_maxid('iddesa','mus_desa');
		exec_query("insert into mus_desa(iddesa,id_kecamatan,nama_desa) values ('".$maxid."','".$id_kecamatan."','".$nama_desa."')");
		$stored = get_data('select iddesa from mus_desa where iddesa='.$maxid);
		if($stored['iddesa']==$maxid){
			echo 'success__';
			$id_desa = $maxid;
		}
		logs('Menambah Desa','Desa '.$nama_desa);
	}
	
	echo $id_desa.'__';
	view_desa();
	
}else if($act=='del_desa'){
	$id_desa = $_POST['id_desa'];
	if(is_numeric($id_desa)){
		$nmdesa = get_data('select nama_desa from mus_desa where iddesa='.$id_desa);
		exec_query("delete from mus_desa where iddesa=".$id_desa);
		echo 'success__';
		view_desa();
		logs('Menghapus Desa','Desa yang dihapus : '.$nmdesa['nama_desa']);
	}
	
}else if($act=='edit_desa'){
	$id_desa = $_POST['id_desa'];
	if(is_numeric($id_desa)){
		$data = get_data("select * from mus_desa where iddesa =".$id_desa);
		$ress = implode($data,'__');
		print_r($ress);
		//echo $ress;
	}else{
		echo 'error';
	}
}



function view_desa(){
	$x = 1;
	$desa = get_datas("select a.nama_kecamatan,b.iddesa,b.nama_desa from mus_kecamatan a, mus_desa b where a.id_kecamatan=b.id_kecamatan order by nama_desa");
            foreach ($desa as $desa) {
                ?>
                <tr>
                    <td><?php echo $x ?></td>
                    <td><?php echo $desa['nama_kecamatan']; ?></td>
                    <td><?php echo $desa['nama_desa']; ?></td>
                    <td>
                        <a href="#modalwin" data-toggle="modal"  class="btn btn-small btn-info bt-edit-desa" name="<?php echo $desa['iddesa']; ?>"><i class="icon-edit icon-white"></i> ubah</a>
                        <a class="btn btn-danger btn-small bt-delete-desa" name="<?php echo $desa['iddesa']; ?>"><i class="icon-trash icon-white"></i> hapus</a>
                    </td>
                </tr>
                <?php
                $x++;
            }
}
?>